#include "lost-kingdom.h"

static pthread_t music_thread;
static int tid;

playsound::playsound(string filename)
{
    if(SDL_WasInit(SDL_INIT_AUDIO) == 0)
    {
        SDL_Init(SDL_INIT_AUDIO);
    }

    Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 4096);

    m_music = Mix_LoadMUS(filename.c_str());
    if(!m_music)
    {
        cerr << "Geluidsbestand " << filename << " kon niet geladen worden " << SDL_GetError() << endl;
        succeeded = false;
    } else {
        succeeded = true;
    }
}


playsound::~playsound()
{
    // just free the music
    if(m_music)
    {
        Mix_FreeMusic(m_music);
    }
}

int playsound::Playmusic(bool looped)
{
    int ret;
    int loops;

    if(looped == true)
        loops = -1;
    else
        loops = 0;
    ret = Mix_PlayMusic(m_music, loops);
    playing = true;

    tid = pthread_create(&music_thread, NULL, loopMus, this);

    return ret;
}

void* loopMus(void* data)
{
    playsound* obj = (playsound*) data;

    for(;;)
    {
        if(!Mix_PlayingMusic())
        {
            obj->setPlaying(false);
            pthread_exit(NULL);
            break;
        }
    }
}
